package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import com.tanhua.model.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //用户登录
    public Map login(String username, String password, String verificationCode, String uuid) {
        //1. 比较用户的验证码与Redis中的验证码
        String redisCode = redisTemplate.opsForValue().get("CODE:" + uuid);
        //1.1. 比较验证码
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(verificationCode)) {
            //1.2 如果错误，抛出异常
            throw new BusinessException("验证码错误");
        }
        //1.3 如果正确，删除Redis中的验证码
        redisTemplate.delete("CODE:" + uuid);
        //2. 比较用户名密码，与数据库中是否一致
        //2.1 根据username获取admin对象
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Admin admin = adminMapper.selectOne(wrapper);
        //2.2 对用户输入的密码进行加密
        password = SecureUtil.md5(password);
        if (admin == null || !admin.getPassword().equals(password)) {
            throw new BusinessException("用户名或密码错误");
        }
        //3. 生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id", admin.getId());
        String token = JwtUtils.getToken(tokenMap);
        //4. 返回
        Map retMap = new HashMap();
        retMap.put("token", token);
        return retMap;
    }

    //用户基本信息
    public AdminVo profile() {
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        AdminVo vo = AdminVo.init(admin);
        return vo;
    }


}
